package com.atguigu4.search_sort.exer2;

/**
 * ClassName: twofeng
 * Description:
 *int[] arr2 = new int[]{2,4,5,8,12,15,19,26,37,49,51,66,89,100};
 * 查找元素5是否在上述数组中出现过？如果出现，输出对应的索引值。
 * @Author liu
 * @Create 2024/8/12 20:24
 * @Version 1.0
 */

//二分法查找 ==>递增或递减
//1.定义目标元素
//2.定义首，尾，找到中间数
//3判断目标元素与中间大小，
//4 大了；首=中+1；小了：尾=中-1
public class twofeng {
    public static void main(String[] args) {
        int[] arr2 = new int[]{2,4,5,8,12,15,19,26,37,49,51,66,89,100};
        int target = 5;
        boolean flag = true;

        int head = 0;
        int end = arr2.length-1;
        while(head<end) {
            int mid = (head + end)/2;
            if (target == arr2[mid]) {
                System.out.print("找到了，" + "在第" + mid + "位");
                flag = false;
                break;
            } else if (target > arr2[mid]) {
                head = mid + 1;
            } else {
                end = mid - 1;
            }
            }
            if (flag) {
                System.out.print("抱歉，没有该数");
        }
    }
}
